<template>
  <div class="image-ai-painting-modal">
    <a-modal
      v-model:open="open"
      :footer="false"
      title="图片扩展"
      width="650px"
      style="text-align: center"
    >
      <a-card>
        <a-row :gutter="16">
          <a-col :span="!paintingImgUrl ? 24 : 12">
            <a-image
              :src="picture.url"
              height="50vh"
              style="object-fit: cover; margin-bottom: 10px"
            />
            <a-button type="primary" @click="doPaintingImage" :loading="!!taskId"
              >扩展
              {{ userStore?.userInfo?.expandCount }}
            </a-button>
          </a-col>
          <a-col :span="paintingImgUrl ? 12 : 0">
            <div v-if="paintingImgUrl">
              <a-image
                :src="paintingImgUrl"
                height="50vh"
                style="object-fit: cover; margin-bottom: 10px"
              />
              <a-button type="primary" @click="handleUpload" :loading="uploadLoading">应用</a-button>
            </div>
          </a-col>
        </a-row>
      </a-card>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import 'vue-cropper/dist/index.css'
import { ref } from 'vue'
import {
  createImageOutPaintingUsingPost,
  getImageOutPaintingTaskUsingGet,
  uploadPictureByUrlUsingPost,
} from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import { useUserStore } from '@/stores/user.ts'

// 获取用户数据
const userStore = useUserStore<API.LoginUserVo>()

const open = defineModel()

interface Props {
  picture: API.PictureVO
  spaceId: number
  onSuccess: (newPicture: API.PictureVO) => void
}

const props = withDefaults(defineProps<Props>(), {})

// 打开modal
const openModal = () => {
  open.value = true
}

defineExpose({
  openModal,
})

// 扩展图片
const taskId = ref('')
const paintingLoading = ref(false)
const doPaintingImage = async () => {
  paintingLoading.value = true
  const res = await createImageOutPaintingUsingPost({
    pictureId: props.picture.id,
    parameters: {
      xScale: 2,
      yScale: 2,
    },
  })
  if (res.data.code === 0 && res.data.data) {
    message.success('任务创建成功，请不要退出，耐心等待')
    taskId.value = res.data.data?.output?.task_id
    startPolling()
  }
}

// 开始轮询
let pollingTimer: any = null

const clearPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
    pollingTimer = null
    taskId.value = null
  }
}
// 扩图结果
const paintingImgUrl = ref('')
const startPolling = () => {
  if (!taskId.value) {
    return
  }
  try {
    pollingTimer = setInterval(async () => {
      const res = await getImageOutPaintingTaskUsingGet({
        taskId: taskId.value,
      })
      if (res.data.code != 0) {
        clearPolling()
        return
      }
      if (res.data.data?.output?.task_status === 'SUCCEEDED') {
        clearPolling()
        paintingImgUrl.value = res.data.data.output.output_image_url
        // 更新用户信息
        userStore.fetchUserInfo()
      } else if (res.data.data?.output?.task_status === 'FAILED') {
        clearPolling()
        message.error(res.data.data.output.message)
      }
    }, 3000)
  } catch (error) {
    console.log(error.message)
    clearPolling()
  }
}

// 上传url图片
const searchParams = ref<API.PictureUploadRequest>({})
const uploadLoading = ref(false)
const handleUpload = async () => {
  uploadLoading.value = true
  try {
    if (props.picture) {
      searchParams.value.id = props.picture.id
    }
    if (paintingImgUrl.value) {
      searchParams.value.fileUrl = paintingImgUrl.value
    }
    const res = await uploadPictureByUrlUsingPost({
      ...searchParams.value,
      spaceId: props.spaceId,
    })
    if (res.data.code != 0) {
      return
    }
    props.onSuccess?.(res.data.data)
    open.value = false
    message.success('应用图片成功')
  } catch (error) {
    console.log(error.message)
  }
  uploadLoading.value = false
}
</script>

<style lang="scss"></style>
